package com.wonderland.sail.mybatis.parser.impl;

import com.wonderland.sail.mybatis.model.Page;
import com.wonderland.sail.mybatis.parser.SqlParser;
import com.wonderland.sail.util.StringUtil;

/**
 * Created by gaoxinyu on 2015-05-20.
 */
public abstract class AbstractSqlParser implements SqlParser {

    protected String getSortSql(Page page) {
        if (isSortFieldEmptyOrIllegal(page)) return "";
        StringBuilder sortSql = new StringBuilder(" order by ");
        String[] sortFields = page.getSortField().split(",");
        String[] sortOrders = getSortOrderArray(page);
        for (int i = 0; i < sortFields.length; i++) {
            String sortField = sortFields[i];
            if (StringUtil.isEmpty(sortField)) {
                break;
            }
            if (sortField.endsWith("IsZh")) {
                getZhSortField(sortSql, sortField);
            } else {
                sortSql.append(sortField);
            }

            if (sortOrders != null) {
                sortSql.append(" ").append(sortOrders[i]);
            }
            sortSql.append(",");
        }
        return sortSql.deleteCharAt(sortSql.length() - 1).toString();
    }

    abstract void getZhSortField(StringBuilder sortSql, String sortField);

    private String[] getSortOrderArray(Page page) {
        String[] sortOrders;
        if (StringUtil.isEmpty(page.getSortOrder())) {
            sortOrders = null;
        } else {
            if (page.getSortOrder().contains(" ")) {
                throw new IllegalArgumentException("sortOrder不能包含空格");
            }
            sortOrders = page.getSortOrder().split(",");
        }
        return sortOrders;
    }

    private boolean isSortFieldEmptyOrIllegal(Page page) {
        if (StringUtil.isEmpty(page.getSortField())) {
            return true;
        }
        if (page.getSortField().contains(" ")) {
            throw new IllegalArgumentException("sortField不能包含空格");
        }
        return false;
    }
}
